package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.mta.pokerstats.Player;

/**
 * Servlet implementation class servletMainPage
 */
public class servletMainPage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public servletMainPage() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	private void  processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String theAction = request.getParameter("action");
        Player viewingPlayer = (Player)request.getSession().getAttribute("viewingPlayer");
        try{
	        if(theAction.equalsIgnoreCase("JoinTeam"))
	        {
	        	String teamToJoinId = request.getParameter("TeamToJoinId");
	        	Player currPlayer = viewingPlayer;
	        	currPlayer.setTeamId(Integer.parseInt(teamToJoinId));
	        	currPlayer.setJoinStatus("Pending");
	        	currPlayer.UpdateInDatabase();
	        }
	        else
	        {
	        	if(theAction.equalsIgnoreCase("changeProfileInfo")){
	        		String userName = request.getParameter("UserNameProfile");
	        		String userPassword = request.getParameter("UserPasswordProfile");
	        		String bDayStr = request.getParameter("UserBirthdayProfile");
	        		Date userBirthday = null;
	        		Player currPlayer = viewingPlayer;
	        		if (bDayStr != null && (bDayStr.length() > 0)){
		        		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
		        		userBirthday = new Date(dateFormatter.parse(bDayStr).getTime());
	        		}
	        		currPlayer.setBirthday(userBirthday);
	        		currPlayer.setName(userName);
	        		currPlayer.setPassword(userPassword);	
	        		currPlayer.UpdateInDatabase();
	        	}
	        }
	   }
        catch (ParseException e){
        	
        }
        finally {            
           out.close();
       }
	}
}